import jwt from 'jsonwebtoken';

// 从环境变量获取密钥，如果没有则使用默认值（生产环境请务必设置环境变量）
const ACCESS_TOKEN_SECRET = process.env.ACCESS_TOKEN_SECRET || 'your-access-token-secret-key-change-in-production';
const REFRESH_TOKEN_SECRET = process.env.REFRESH_TOKEN_SECRET || 'your-refresh-token-secret-key-change-in-production';

// Token 过期时间
const ACCESS_TOKEN_EXPIRES_IN = '15m'; // 15分钟
const REFRESH_TOKEN_EXPIRES_IN = '7d'; // 7天

export interface TokenPayload {
    userId: string;
    email: string;
    username: string;
}

/**
 * 生成 access_token
 */
export function generateAccessToken(payload: TokenPayload): string {
    return jwt.sign(payload, ACCESS_TOKEN_SECRET, {
        expiresIn: ACCESS_TOKEN_EXPIRES_IN,
    });
}

/**
 * 生成 refresh_token
 */
export function generateRefreshToken(payload: TokenPayload): string {
    return jwt.sign(payload, REFRESH_TOKEN_SECRET, {
        expiresIn: REFRESH_TOKEN_EXPIRES_IN,
    });
}

/**
 * 验证 access_token
 */
export function verifyAccessToken(token: string): TokenPayload {
    try {
        return jwt.verify(token, ACCESS_TOKEN_SECRET) as TokenPayload;
    } catch (error) {
        throw new Error('无效的 access_token');
    }
}

/**
 * 验证 refresh_token
 */
export function verifyRefreshToken(token: string): TokenPayload {
    try {
        return jwt.verify(token, REFRESH_TOKEN_SECRET) as TokenPayload;
    } catch (error) {
        throw new Error('无效的 refresh_token');
    }
}

/**
 * 从 refresh_token 中获取过期时间（用于数据库存储）
 */
export function getRefreshTokenExpiry(): Date {
    const now = new Date();
    const days = 7; // 7天
    now.setDate(now.getDate() + days);
    return now;
}